﻿
Ext.define('Ext.data.flash.BinaryXhr', {

    statics: {

        flashPluginActivated: function () {
            Ext.data.flash.BinaryXhr.flashPluginActive = true;
            Ext.data.flash.BinaryXhr.flashPlugin = document.getElementById("ext-flash-polyfill");
            Ext.GlobalEvents.fireEvent("flashready");
        },


        flashPluginActive: false,


        flashPluginInjected: false,



        connectionIndex: 1,


        liveConnections: {},


        flashPlugin: null,


        onFlashStateChange: function (javascriptId, state, data) {
            var connection;

            connection = this.liveConnections[Number(javascriptId)];
            if (connection) {
                connection.onFlashStateChange(state, data);
            }
            else {
                Ext.warn.log("onFlashStateChange for unknown connection ID: " + javascriptId);
            }
        },


        registerConnection: function (conn) {
            var i = this.connectionIndex;
            this.conectionIndex = this.connectionIndex + 1;
            this.liveConnections[i] = conn;
            return i;
        },


        injectFlashPlugin: function () {
            var me = this,
                flashLoaderPath, flashObjectPath;






            me.flashPolyfillEl = Ext.getBody().appendChild({
                id: 'ext-flash-polyfill',
                cn: [
                    {
                        tag: 'p',
                        html: 'To view this page ensure that Adobe Flash Player version 11.1.0 or greater is installed.'
                    },
                    {
                        tag: 'a',
                        href: 'http://www.adobe.com/go/getflashplayer',
                        cn: [
                            {
                                tag: 'img',
                                src: window.location.protocol + '//www.adobe.com/images/shared/download_buttons/get_flash_player.gif',
                                alt: 'Get Adobe Flash player'
                            }
                        ]
                    }
                ]
            });



            flashLoaderPath = [Ext.Loader.getPath('Ext.data.Connection'), '../../../plugins/flash/swfobject.js'].join('/');
            flashObjectPath = "/plugins/flash/FlashPlugin.swf";
            flashObjectPath = [Ext.Loader.getPath('Ext.data.Connection'), '../../plugins/flash/FlashPlugin.swf'].join('/');
            if (Ext.flashPluginPath) {
                flashObjectPath = Ext.flashPluginPath;
            }

            Ext.Loader.loadScript({
                url: flashLoaderPath,
                onLoad: function () {

                    var swfVersionStr = "11.4.0";

                    var xiSwfUrlStr = "playerProductInstall.swf";
                    var flashvars = {};
                    var params = {};
                    params.quality = "high";
                    params.bgcolor = "#ffffff";
                    params.allowscriptaccess = "sameDomain";
                    params.allowfullscreen = "true";
                    var attributes = {};
                    attributes.id = "ext-flash-polyfill";
                    attributes.name = "polyfill";
                    attributes.align = "middle";
                    swfobject.embedSWF(
                        flashObjectPath, "ext-flash-polyfill",
                        "0", "0",
                        swfVersionStr, xiSwfUrlStr,
                        flashvars, params, attributes);
                },
                onError: function () {
                    Ext.Error.raise("Could not load flash-loader file swfobject.js from " + flashLoader);
                },
                scope: me
            });

            Ext.data.flash.BinaryXhr.flashPluginInjected = true;
        }
    },


    readyState: 0,


    status: 0,



    statusText: "",


    responseBytes: null,


    javascriptId: null,



    constructor: function (config) {

        if (!Ext.data.flash.BinaryXhr.flashPluginInjected) {
            Ext.data.flash.BinaryXhr.injectFlashPlugin();
        }
        var me = this;

        Ext.apply(me, config);
        me.requestHeaders = {};
    },


    abort: function () {
        var me = this;

        if (me.readyState == 4) {
            Ext.warn.log("Aborting a connection that's completed its transfer: " + this.url);
            return;
        }

        me.aborted = true;

        if (!Ext.data.flash.BinaryXhr.flashPluginActive) {
            Ext.GlobalEvents.removeListener("flashready", me.onFlashReady, me);
            return;
        }

        Ext.data.flash.BinaryXhr.flashPlugin.abortRequest(me.javascriptId);

        delete Ext.data.flash.BinaryXhr.liveConnections[me.javascriptId];
    },


    getAllResponseHeaders: function () {
        var headers = [];
        Ext.Object.each(this.responseHeaders, function (name, value) {
            headers.push(name + ': ' + value);
        });
        return headers.join('\x0d\x0a');
    },


    getResponseHeader: function (header) {
        var headers = this.responseHeaders;
        return (headers && headers[header]) || null;
    },


    open: function (method, url, async, user, password) {
        var me = this;
        me.method = method;
        me.url = url;
        me.async = async !== false;
        me.user = user;
        me.password = password;

        if (!me.async) {
            Ext.Error.raise("Binary posts are only supported in async mode: " + url);
        }
        if (me.method != "POST") {
            Ext.log.warn("Binary data can only be sent as a POST request: " + url);
        }
    },


    overrideMimeType: function (mimeType) {
        this.mimeType = mimeType;
    },


    send: function (body) {
        var me = this;
        me.body = body;
        if (!Ext.data.flash.BinaryXhr.flashPluginActive) {
            Ext.GlobalEvents.addListener("flashready", me.onFlashReady, me);
        } else {
            this.onFlashReady();
        }
    },


    onFlashReady: function () {
        var me = this, req, status;
        me.javascriptId = Ext.data.flash.BinaryXhr.registerConnection(me);


        req = {
            method: me.method,
            url: me.url,
            user: me.user,
            password: me.password,
            mimeType: me.mimeType,
            requestHeaders: me.requestHeaders,
            body: me.body,
            javascriptId: me.javascriptId
        };
        status = Ext.data.flash.BinaryXhr.flashPlugin.postBinary(req);
    },


    setReadyState: function (state) {
        var me = this;
        if (me.readyState != state) {
            me.readyState = state;
            me.onreadystatechange();
        }
    },


    setRequestHeader: function (header, value) {
        this.requestHeaders[header] = value;
    },


    onreadystatechange: Ext.emptyFn,


    parseData: function (data) {
        var me = this;

        this.status = data.status || 0;

        me.responseHeaders = {};
        if (me.mimeType) {
            me.responseHeaders["content-type"] = me.mimeType;
        }
        if (data.reason == "complete") {

            this.responseBytes = data.data;
            me.responseHeaders["content-length"] = data.data.length;
        } else if (data.reason == "error" || data.reason == "securityError") {
            this.statusText = data.text;
            me.responseHeaders["content-length"] = 0;
        }
        else {
            Ext.Error.raise("Unkown reason code in data: " + data.reason);
        }
    },


    onFlashStateChange: function (state, data) {
        var me = this;
        if (state == 4) {

            me.parseData(data);

            delete Ext.data.flash.BinaryXhr.liveConnections[me.javascriptId];
        }
        me.setReadyState(state);
    }

});
